package com.controller;
import com.entity.MethodLog;
import com.service.AsAccountDetailService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

@Controller
public class ReportFormController
{
    @Resource
    private AsAccountDetailService asAccountDetailService;

    //前往代理商流水报表页面
    @RequestMapping( value = "/toAgentBalanceReportPage" )
    public String toAgentBalanceReportPage()
    {
        return "reportForm/agentBalanceReport";
    }

    //显示代理商流水报表
    @RequestMapping( value = "/showAgentBalanceReportPage" , produces = "application/json;charset=UTF-8" )
    @ResponseBody
    @MethodLog( operateInfo = "查看代理商流水报表" )
    public String showAgentBalanceReportPage( String start , String end ,
            Integer page , @RequestParam(value = "rows") Integer size )
    {
        String jsonStr = asAccountDetailService.returnAgentBalanceReportJsonStr( start , end , page , size );
        return jsonStr;
    }

    //生成excel
    @RequestMapping( value = "/downloadExcel" )
    @MethodLog( operateInfo = "下载代理商流水报表" )
    public void downloadExcel( String excelType , HttpServletRequest req , HttpServletResponse resp )

    {
        String path = req.getSession().getServletContext().getRealPath( "excel" + File.separator );
        File pathFile = new File( path );
        if( !pathFile.exists() )
        {
            pathFile.mkdirs();
        }
        String fileName = "";
        switch( excelType )
        {
            case "agentBalanceExcel":
                fileName = asAccountDetailService.createAgentBalanceExcel( path );
                break;
        }
        resp.setContentType( "application/msexcel;charset=UTF-8" );
        resp.setCharacterEncoding( "UTF-8" );
        try
        {
            resp.setHeader( "Content-disposition" , "attachment;filename=" +
                    new String( fileName.getBytes("UTF-8"), "ISO8859-1") );
        }
        catch ( UnsupportedEncodingException e )
        {
            e.printStackTrace();
        }
        try
        {
            InputStream in = new FileInputStream( path + File.separator + fileName );
            OutputStream os = resp.getOutputStream();
            byte [] b = new byte[in.available()];
            in.read( b );
            os.write( b );
            os.flush();
            in.close();
            os.close();
        }
        catch ( IOException e )
        {
            System.out.println( "ReportFormController的downloadExcel方法出错" );
            e.printStackTrace();
        }

    }

}
